import { useRoute } from "vue-router";
import type { PermissionCode } from "/@/api/permissionCode";
import { OperPermissionType } from "/@/api/aiot/role/models";
import { useUserStore } from "/@/stores/aiot/user";

export function usePermission(options?: { routeName: string }) {
  let routeName = options?.routeName;
  if (!routeName) {
    const route = useRoute();
    routeName = route.name as string;
  }
  const userStore = useUserStore();
  const permission = userStore.getPermissionByName(routeName);
  // const operationsType = ref<OperPermissionType | null | undefined>(permission ? permission.operationsType : null);
  //项目相关的权限用的operationType，其它用operationsType
  const operationsType = permission ? permission.operationsType || permission.operationType : null;
  function judgePermissionByOperType(operType: OperPermissionType = OperPermissionType.MANAGE) {
    if (userStore.isAdmin()) return true;
    if (operType === OperPermissionType.CHECK) {
      return !!operationsType;
    }
    return operationsType === OperPermissionType.MANAGE;
  }
  function judgePermissionByCode(permissonCode: PermissionCode) {
    if (userStore.isAdmin()) return true;
    if (permission) {
      const opers = permission.operations;
      return operationsType === OperPermissionType.MANAGE || !!opers?.find((oper) => oper.code === permissonCode);
    }
    return false;
  }
  return {
    operationsType,
    judgePermissionByOperType,
    judgePermissionByCode,
  };
}
